<template>
	<div class="authorize">
		<bread-crumb>
			<template slot="node">
				<li>
					<router-link to="/uc/MySponsored">我發起的投票</router-link>
				</li>
			</template>
			投票詳情
		</bread-crumb>
		<div class="uc-body">
			<div class="manage-detail">
				<manage-detail
					:vote-object="voteObject"
					:timely-object-vote="timelyObjectVote"
					:timely-object-contest="timelyObjectContest"
					:review-object-contest="reviewObjectContest"
					:loading-vote="loadingVote"
					:loading-contest="loadingContest"
				>
				</manage-detail>
				<el-divider content-position="left">資金數據</el-divider>
				<div class="manage-detail-row">
					<span class="label">初始本金：</span>
					<span>{{precisionDivision(competitioznPrizePool.total_initial,betCoinData.decimal) }} {{betCoinData.symbol}}</span>

				</div>
				<div class="manage-detail-row">
					<span class="label">當前獎池待領：</span>
					{{ precisionDivision(competitioznPrizePool.pool_amout,betCoinData.decimal)}}
					{{betCoinData.symbol}}
				</div>
				<div class="manage-detail-row">
					<span class="label">玩家獎勵：</span>
					<!--覆核後後待比較結果已經塵埃落定了，再展示這個獎勵方是有效-->
					<span v-if="reviewObjectContest.reviewState==7">
						{{ precisionDivision(competitioznPrizePool.lose_money,betCoinData.decimal)}}
					</span>
					{{betCoinData.symbol}}
				</div>


				<el-divider content-position="left">收益數據（{{betCoinData.symbol}}）</el-divider>
				<div class="manage-detail-row" v-html="earningsText"></div>

				<el-divider content-position="left">可用操作</el-divider>
				<div class="manage-detail-row" v-if="numberVotesToBeReceived>0">
					<!--賽事完成了，足球收益能領取也敲定了，可以算出來足球應該給多少了。顯示出來完整收益-->
					<div
						v-html="receivableAmount">
					</div>
				</div>

				<el-divider></el-divider>
				<!--***************************************控制按钮***************************************-->

				<div class="btn-group">

					<!--無論時投票成功，還是失敗，一鍵領取後，票數歸零。判斷自己可領取數量，來按鈕就顯示隱藏了-->
					<div v-if="numberVotesToBeReceived>0">
						<!--投票失敗-->
						<div v-if="timelyObjectVote.status==3">
							<el-button type="warning" @click="getBenefits">失敗取回票數與基本金</el-button>
						</div>

						<!--投票作廢-->
						<div v-if="timelyObjectVote.status==2">
							<el-button type="danger" @click="getBenefits">作廢取回票數與基本金</el-button>
						</div>

						<!--投票成功賽事開啟，並且覆核已通過 -->
						<div v-if="reviewObjectContest.reviewState == 7 && timelyObjectVote.status==7 ">
							<el-button type="danger" @click="getBenefits">一鍵領取票數、本金與獎勵</el-button>
						</div>
					</div>

					<!--賽事開啟後：且投注時間已完，並且沒有覆核對象（reviewId為0）-->
					<div v-if="visibleResultWriteButton">
						<el-button type="success" @click="actShowContestResultWrite">填寫賽事結果</el-button>
					</div>
					<!--投票成功賽事開啟，並且覆核被駁回 -->
					<div v-if="reviewObjectContest.reviewState == 2 && timelyObjectVote.status==7 ">
						<span>覆核沒有通過，請重新填寫</span>
						<el-button type="danger" @click="actShowContestResultWrite">重新填寫賽事結果</el-button>
					</div>

				</div>
			</div>
		</div>
		<!--******************************************* 结果填写弹层 ***********************************************-->
		<el-dialog
			title=""
			width="340px"
			top="calc(50vh - 250px)"
			:append-to-body="true"
			:visible.sync="visibleResultWrite"
			:before-close="onCloseResultWrite"
		>
			<div class="dialog-detail-module">
				<div class="module-title">賽事結果填寫</div>
				<div class="line"></div>
				<div class="module-wrap">
					<div class="v-row">
						<span class="label">參賽隊伍：</span>
						<div class="con">
							{{timelyObjectContest.contestMaster}}
							<img src="@/assets/vs.svg" alt="">
							{{timelyObjectContest.contestBranch}}
						</div>
					</div>
					<div class="v-row">
						<span class="label">賽事結果（主隊）</span>
					</div>
					<div class="v-row">
						<el-radio-group v-model="voteInput">
							<el-radio-button label="0">胜</el-radio-button>
							<el-radio-button label="1">平</el-radio-button>
							<el-radio-button label="2">负</el-radio-button>
						</el-radio-group>
					</div>

				</div>
				<div class="line"></div>
				<div class="btn-group">
					<el-button
						type="primary" size="big" icon="el-icon-s-promotion" round
						:loading="submiting"
						:disabled="submiting"
						@click="actSubmitResultScore">
						提交比賽結果
					</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>

//数据
import breadCrumb from '../components/breadCrumb.vue'
import manageDetail from "./components/manageDetail";
import { mixins } from '@/mixins/mixins'
import { mixinsUtils } from '@/mixins/mixins.utils'
import { mixinsManage } from "@/views/manage/js/manage.mixins"
import { contestMixinsGlobal } from '@/views/contestHall/contest.mixins.global'
import {mixinsVoteDetail} from "./js/mixins.vote.detail";

import {
	 tronViewGamePlayMethodExpand,
	apiVotingAnalysisServe,
} from "@/views/uc/manage/js/manage.user.lib";
import {
	tronTokenAnalyze,
	tronGameIncomeCalculationList,
	userEndsGameCheck, tronVotingIncomeAmount
} from "./js/manage.user.lib";

import {footContract} from "../../manage/js/manage.lib";
import { dev, hex2Num } from '@/libs/tron.lib'
import {
	encodeParams,
	msgInterface,
	smartContractBroadcastCallback,
	smartContractConfirmCallback,
} from "@/libs/site.utils";
import { getEffectiveValueForContest2 } from "@/views/manage/js/manage.func";
import { apiRequestGameTron, tronGetGameKeyData } from "@/views/contestHall/contest.func"; //vuex工具
//导出
export default {
	name      : "manageMySponsoredDetail",
	components: { breadCrumb,manageDetail },
	mixins: [mixins,  mixinsUtils, mixinsManage, contestMixinsGlobal, mixinsVoteDetail],
	data () {
		return {
			//////////////////////简单值////////////////////////////
			earningsText:"",//收益文本描述
			receivableAmount:"",//能领取到的资金
			//////////////////////复杂值////////////////////////////

			//奖池数据
			competitioznPrizePool:{},
			//提交数据对象
			voteInput:"",
		}
	},
	computed:{
		/**
		 * 是否显示赛事结果填写按钮，条件如下：
		 * 投票成功赛事开启
		 * 并且已到TZ截止时间
		 * 并且复核状态是第一次（复核另外有个驳回，状态码不一样）
		 * @returns {boolean}
		 */
		visibleResultWriteButton(){
			let _diff = Date.parse(this.timelyObjectContest.endTimeStr) / 1000 - this.timestampNow //投票结束时间差
			if(_diff < 0 && this.reviewObjectContest.reviewId==0 && this.timelyObjectVote.status==7){
				return true
			}else{
				return false
			}
		}
	},
	created () {
		//数据加载入口
		this.getMySponsoredVoteDetail(()=> {
		    this.dataReadDispatch();
		}) //请求数据
	},
	mounted () {
	},

	methods: {

		// 加载数据（我发起的和我参与的这里不一样）
		dataReadDispatch() {
			this.checkDecimal();	//检查精度加载
			this.viewProposalInfo([this.id]);//查看投票信息
			this.getTimelyDataOfContestFromChain(this.playId);//读取赛事实时数据
			this.getReviewInfo(this.id);//查看复审信息。有则有,没有则没有
			this.getBalanceOfVotes();	//获取我能领取的金额，一键领了就空了，变量
			this.getGamePlayMethodExpand(this.playId);//读取赛事实时资金数据数据(发起者)

		},

		//读取本游戏支持的币种信息
		checkDecimal() {
			let that = this;
			//获取币种精度
			let bet_decimal = that.betCoinData.decimal;
			if (!that.betCoinData.decimal || parseInt(bet_decimal) <= 0) {
				console.log('正在检查币种信息...');
				tronTokenAnalyze(this.timelyObjectContest.betToken, this.sender, (o)=>{
					that.betCoinData = o
					this.funcAfterSupportCoinData()
				})
				//开启递归调用
				this.contractInfoTime = setTimeout(() => {
					that.checkDecimal()
				}, 5000);
				return;
			} else {//支持的币种信息才能继续下一步
				this.funcAfterSupportCoinData()
			}
		},

		//依赖于加载支持币种后才执行的东西
		funcAfterSupportCoinData(){
			this.gameIncomeCalculationList(this.playId);//收益数据
			this.getVotingIncomeAmount();//获取我能领取的金额，用作做显示收益的，常量
		},

		//todo 整改提取
		//读取赛事实时数据并解析
		getTimelyDataOfContestFromChain(id){
			this.loadingContest = true
			//从赛事合约请求实时数据并解析
			tronGetGameKeyData(id).then((rs) => {
				// let {param} = rs
				let _analyzing2 = getEffectiveValueForContest2(rs)
				dev && console.log('/////////////////////////////////////////////请求单个赛事实时数据解析结果数据:',_analyzing2)
				this.timelyObjectContest.status = _analyzing2[1] //取得状态
				this.timelyObjectContest.odds = _analyzing2[2] //取得P率

				//以下位数截取仅供胜平负参考，因为随着赔率长度不一样，返回长度不bytes一样。需注意
				let matchResults = (rs + "").substring(1408, 1472);
				//10的0次方等于1，除以1数字不变。使用该方法+零次方目的：使用hex转换数字的功能，并保持数值不做次方改变
				matchResults = hex2Num(matchResults, 0);
				this.timelyObjectContest.winning = matchResults;

				this.loadingContest = false
			})
		},

		// 从赛事合约读取资金方面的数据，并解析
		getGamePlayMethodExpand(param) {
			let that = this;
			tronViewGamePlayMethodExpand(param).then((rs) => {
				//解析合约返回（目前使用服务器的接口来解析）
				apiRequestGameTron({
					"type": "viewGamePlayMethodExpand",
					'act': 'returnDataAnalyze',
					"param": rs
				}).then(result => {
					let data = result;
					if (data.resultFlag != true) {
						return;
					}
					this.competitioznPrizePool=data.data;
				}).catch(err => {
					console.log(err)
				})
			});
		},

		// 加载收益数据
		gameIncomeCalculationList(id) {
			let that = this;
			//0,1,2标识胜平负，按下标传上去
			tronGameIncomeCalculationList(id, [0, 1, 2]).then((rs) => {
				//解析合约返回（目前使用服务器的接口来解析）
				apiRequestGameTron({
					"type": "gameIncomeCalculationList",
					'act': 'returnDataAnalyze',
					"param": rs
				}).then(result => {
					let data = result;
					if (data.resultFlag != true) {
						return;
					}
					let text = that.gameIncomeCalculationConvertTextSPF(data.data);
					that.earningsText = text;
				}).catch(err => {
					console.log(err)
				})
			});
		},

		//计算赛事各结果对应资金数据，并转换成文本
		gameIncomeCalculationConvertTextSPF(data) {
			let logoArr = ['勝', '平', '負']
			let decimal = Math.pow(10, this.betCoinData.decimal);
			let text="<div>";

			//賠付金額
			let dataArr = data.profit_and_loss;
			//投注項金額
			let amountOfBet = data.odds_balances;

			//獲取本金
			text += '<div>賽事初始本金：' + parseInt(data.total_amout) / decimal + "</div>";
			//調用得是區塊鏈計算方法。計算每個項再組合返回，所以每一個項總有重複得數據
			//所以每一個投注項都由總投注金額，取其中一個，訪問裡面第0個元素即可
			text += '<div>賽事投注金額：' + parseInt(dataArr[0][0]) / decimal + "</div>";
			text += '<div>項目方手續費：' + parseInt(dataArr[0][3]) / decimal + '</div>';

			for (let index in dataArr) {
				let data = dataArr[index];
				text += '<div>投注項[' + logoArr[index] + ']——投注金額：' + amountOfBet[index] / decimal + ',&nbsp;&nbsp;需要賠付金額：' + data[1] / decimal + ',&nbsp;&nbsp;投票方總收益：' + data[2] / decimal + "</div>";
			}
			text += '</div>'
			return text;
		},

		//提交赛事结果
		actSubmitResultScore () {
			let that = this;

			// 验证分数填写（兼容多竞技则要重改）
			if(this.voteInput==''){
				this.$notify({title:'錯誤',type:'error',message:'請選擇比賽結果'})
				return false
			}

			//执行下一步
			this.submiting = true
			const ACTION_TITLE = ``
			const ACTION = this.LangSet(['上傳賽事結果:', 'update result'])

			let proposalId = this.voteObject.proposalId;
			let rsarr = this.voteInput;
			let foorid = this.voteObject.externalLinkId;

			const parameter = [
				{type: 'uint256', value: foorid},
				{type: 'uint256', value: rsarr},
			]

			let param = encodeParams(parameter);

			//执行投票。传递参数。参数转换bytes
			let addParameters = "0x" + param;

			//上链
			let remark = ACTION_TITLE + "" + rsarr;
			msgInterface(ACTION, 0, 1, '','');//等待钱包确认
			userEndsGameCheck(
				proposalId,
				footContract,
				addParameters,
				remark,
				this.sender,
				smartContractBroadcastCallback(ACTION,ACTION_TITLE,(status,txid)=> {
					this.submiting = false //恢复可提交
					this.visibleResultWrite = false //关闭
					console.log('hash:',txid)
					if (status == 1) {
						apiVotingAnalysisServe({}, txid); //通知服务器根据hash爬新数据
						setTimeout(() => {
							that.getReviewInfo(that.id);//重新读取复核数据
						},3000)
						setTimeout(() => {
							that.getReviewInfo(that.id);//重新读取复核数据,再读一次
						},6000)
					}
				}),
				smartContractConfirmCallback(ACTION,ACTION_TITLE)
			)
		},


		//////////////////////////////////////////////// 交互 /////////////////////////////////////////////////
		//////////////////////////////////////////////// 交互 /////////////////////////////////////////////////
		//////////////////////////////////////////////// 交互 /////////////////////////////////////////////////
		//打开赛事结果填写
		actShowContestResultWrite(){
			this.visibleResultWrite = true
		},



		// 查看可以拿到的金额（发起人和投票人不一样）
		getVotingIncomeAmount() {
			let that = this;
			let id = this.id;
			tronVotingIncomeAmount(this.sender, this.sender, id, (rs) => {
				console.log(rs,rs)
					//解析合约返回（目前使用服务器的接口来解析）
					apiRequestGameTron({
						"type": "votingIncomeAmount",
						'act': 'returnDataAnalyze',
						"param": rs
					}).then(result => {
						let data = result;
						if (data.resultFlag != true) {
							return;
						}
						let body = data.data;

						let _decimal = that.betCoinData.decimal;
						let symbol_  = that.betCoinData.symbol;

						//质押票，8个精度。收益的赛事，usdt 6个精度
						let control = (parseInt(body.locked) / 100000000).toFixed(3);
						let income = (parseInt(body.transfer_amount_) / Math.pow(10, _decimal)).toFixed(3);

						//写入治理领取金额
						let earningsText = "";
						earningsText = `<div>質押票數：${control} ${that.xg.name} (發起票+贊成票+反對票)</div>`;
						//投票完成了，可以知道足球的收益了，近而算出足球領取多少
						if (that.reviewObjectContest.reviewState == 7) {
							earningsText += "<div>賽事盈虧：" + income + symbol_ + " （包括本金）</div>";
						}else{
							earningsText += "<div>開獎後才有數據</div>";
						}
						if(this.timelyObjectVote.status==2 || this.timelyObjectVote.status==3){
							earningsText += "<div>賽事本金：" + this.precisionDivision(this.competitioznPrizePool.total_initial, _decimal) + symbol_ + " </div>";
						}
						that.receivableAmount = earningsText;
					}).catch(err => {
						console.log(err)
					})
				}
			);
		},


		//关闭结果填写,如果绑定了关闭回调，则要调用done()
		onCloseResultWrite(done){
			done()
		},

		////////////////////////////////////////////////其它/////////////////////////////////////////////////
		////////////////////////////////////////////////其它/////////////////////////////////////////////////
		////////////////////////////////////////////////其它/////////////////////////////////////////////////
		//刷新，筛选
		reFresh () {

		},


	},
	beforeDestroy () {
		window.clearTimeout(this.contractInfoTime);
		clearInterval(this.timerProposal)
	},
}
</script>

<style lang="less" scoped>
/*公共变量*/
@import '~@/assets/global.less';

//单独控制弹层样式细节
.dialog-detail-module {
	.module-wrap {
		.v-row {padding:3px 0;}
	}
	.btn-group{
	}
}
/************************************适应***************************************/
@media screen and (max-width: @MINSCREEN) {

}
</style>
